<?php
defined('_JEXEC') or die;

jimport('joomla.application.component.modeladmin');

class SanphamModelPosts extends JModelAdmin{
	
	protected $_query = NULL;
	
	function __construct(){
		parent::__construct();
		global $app;
		
		$this->setState('limit', $app->getUserStateFromRequest('posts.limit','limit',$app->getCfg('list_limit')));
		$this->setState('limitstart', $app->getUserStateFromRequest('posts.limitstart','limitstart',0));
		$this->setState('filter_search', $app->getUserStateFromRequest('posts.filter_search','filter_search'));
		
		if ($this->_query == NULL) {
			$this->_buildQuery();
		}
	}
			
	public function getForm($data = array(), $loadData = true)
	{
		$form = $this->loadForm('com_sanpham.posts', 'posts', array('load_data'=>$loadData));
		
		if (empty($form)) {
			return false;
		}		
		return $form;
	}
	
	//override phương thức
	protected function loadFormData(){
		$id = JRequest::getVar('cid');
		if ($id[0]) {
			$this->_db->setQuery("SELECT * FROM #__posts WHERE id = $id[0]");
			return $this->_db->loadAssoc();
		}
	}
	
	public function populateState() {	
		global $app;	
		$this->setState('filter_order', $app->getUserStateFromRequest('posts.filter_order','filter_order','created'));
		$this->setState('filter_order_Dir', $app->getUserStateFromRequest('posts.filter_order_Dir','filter_order_Dir','DESC'));
	}
	
	public function changeState($id,$field,$state,$ids)
	{	
		$db 	= $this->getDbo();
		$query	= $db->getQuery(true);
		if(is_array($ids)){
			$ids = implode( ',', $ids );
		}
		$query->update('#__posts')->set("$field = $state")->where("$id IN ($ids)");
		$db->setQuery($query);
		$db->query();
	}
	
	public function getData()
	{
		$db 	= $this->getDbo();
		if ($this->getState('limit')) {
			$db->setQuery($this->_query,$this->getState('limitstart'),$this->getState('limit'));
		}
		return $db->loadObjectList();
	}
	
	public function delData($ids)
	{
		if(is_array($ids)){
			$ids = implode( ',', $ids );
		}
		$db 	= $this->getDbo();
		$query	= $db->getQuery(true);
		$query->delete('#__posts')
			  ->where("id IN ($ids)");
		$db->setQuery($query);
		$db->query();
		//return true;
	}
	
	public function getPagination()
	{
		jimport('joomla.html.pagination');
		$total 				= $this->_getListCount($this->_query);
		return $pagination = new JPagination($total, $this->getState('limitstart'), $this->getState('limit'));
	}
	
	private function _buildQuery()
	{
		$db 	= $this->getDbo();
		$query	= $db->getQuery(true);
		
		$query->select('*');
		$query->from('#__posts');
		$query->order($db->getEscaped($this->getState('filter_order')) . ' ' . $db->getEscaped($this->getState('filter_order_Dir')));
		if ($this->getState('filter_search')) {
			$query->where("title LIKE '%".$this->getState('filter_search')."%' ");
			//$query->clear('where');
			//$query->where("id > 15");
		}
		$this->_query = $query;
	}
}